<style lang="scss" scoped="">
    @import "../utils/base.scss";
    .my_cnetnt{
        margin-top: 8px;
        padding: 10px;
        min-height: calc(100vh - 176px);
        width: 100%;
        background-color: #FFFFFF;
    }
    .ivu-table-overflowX {
    	overflow-x: hidden;
	}
</style>
<template>
	<div style="width: 100%;height:calc(100vh - 118px);">
		<pheader :width="'15%'">
            <template slot="left">休假委托管理</template>
            <div style="text-align: right;margin-right: 32px;" slot="right">
                <Button type="primary" size="small" @click="addVacation()">新增</Button>
            </div>
        </pheader>
		<div class="my_cnetnt">
			<Table border :columns="columns" :data="data" :loading="tableLoading">
	          <template slot-scope="{row, index}" slot="status">
	          	<template v-if="row.cancel === '1'">
	          		<span>提前结束</span>
	          	</template>
	            <template v-else>
	            	<span v-if="row.endTime>nowTime">休假中</span>
	            	<span v-else>已结束</span>
	            </template>
	          </template>
	          <template slot-scope="{row, index}" slot="action">
	          		<div v-if="row.cancel === '1' || row.endTime < nowTime">
	          			<span>不可操作</span>
	          		</div>
                   	<div v-else style="display: inline-block;">
                        <a href="javascript:void(0)" @click="editVacation(row)">
                            <div class="text_link" style="width: 50px;">
                                编辑
                            </div>
                        </a>
                        <a href="javascript:void(0)" @click="cancelVacation(row.id)">
                            <div class="text_link" style="width: 80px;">
                                取消休假
                            </div>
                        </a>
                    </div>
	          </template>
			</Table>
			<div style="margin: 10px;overflow: hidden">
	          	<div style="float: right;">
	            	<Page :current="page" :total="total" show-total show-elevator show-sizer @on-change="changePage"
	              @on-page-size-change="changePageSize"></Page>
	        	</div>
	        </div>
		</div>
		<Modal v-model="modal" :title="vacation.isupdate?'编辑休假':'新增休假'" @on-ok="setVacation" @on-cancel="cancel('vacationInfo')" :mask-closable="false" width="720" :loading="modalLoading">
			<Form :model="vacation" ref="vacationInfo" :label-width="120" label-position="left" :rules="vacationRules">
				<Row>
					<Col span="11">
						<FormItem label="被委托人：" prop="deleUserId">
							<component ref="inputSearch" :dataList="peopleList" :checkLable="vacation.deleUserId" :is="'inputSearch'" :multiple="false" :isSysUser="false" @on-change="getPeople"></component>
						</FormItem>
					</Col>
				</Row>
				<Row>
					<Col span="11">
						<FormItem label="委托开始时间：" prop="startTime">
							<DatePicker v-model="vacation.startDate" type="datetime" placeholder="委托开始日期" :clearable="false" @on-change="changeStartDate" :options="dateOptions" :transfer="true"></DatePicker>
						</FormItem>
					</Col>
					<Col span="11" style="left:5%">
						<FormItem label="委托结束日期：" prop="endTime">
							<DatePicker v-model="vacation.endDate" type="datetime" placeholder="委托结束日期" :clearable="false" @on-change="changeEndDate" :options="dateOptions" :transfer="true"></DatePicker>
						</FormItem>
					</Col>
				</Row>
				<Row>
					<Col span="23">
						<FormItem label="委托原因：" prop="reason">
							<Input v-model="vacation.reason" maxlength="200" show-word-limit type="textarea" :rows="3" placeholder="请输入休假委托原因"/>
						</FormItem>
					</Col>
				</Row>
			</Form>
		</Modal>
	</div>
</template>
<script>
	import ajax from "../ajax_util"
	import pheader from "../comp_chatter/pheader"
	import inputSearch from '../base/input_search'

	export default {
        components: {
        	pheader,inputSearch
        },

		data () {
            const validateDeleUserId = (rule, value, callback) => {
                if (this.vacation.deleUserId === undefined || this.vacation.deleUserId === null || this.vacation.deleUserId < 1) {
                    callback(new Error('请选择被委托人'));
                }else{
                    callback()
                }
            };
            const validateStartTime = (rule, value, callback) => {
                if (this.vacation.startTime === undefined || this.vacation.startTime === null || this.vacation.startTime < 1) {
                    callback(new Error('请选择委托开始日期'));
                }else{
                	callback()
                }
            };
            const validateEndTime = (rule, value, callback) => {
				if(this.vacation.endTime === undefined || this.vacation.endTime === null || this.vacation.endTime < 1){
                	callback(new Error('请选择委托结束日期'));
                }else{
                	console.log("0000",this.vacation.startTime - this.vacation.endTime);
                	if(this.vacation.startTime > this.vacation.endTime){
                		callback(new Error('开始日期不能大于结束日期'));
                	}else{
                		callback()
                	}
                }
            };
			return {
      			columns:[
                    {
						title: ' ',
                        type: 'index',
                        width: 60,
                        align: 'center'
                    },
      				{
      					title: '被委托人',
                    	key: 'deleUserName',
                    	width: 150
      				},
      				{
      					title: '开始时间',
                    	key: 'startDate',
                    	width: 200
      				},
      				{
      					title: '结束时间',
                    	key: 'endDate',
                    	width: 200
      				},
      				{
      					title: '休假原因',
                    	key: 'reason'
      				},
      				{
      					title: '状态',
                    	slot: 'status',
                    	width: 100
      				},
      				{
      					title: '操作',
      					slot: 'action',
      					width: 180
      				}
      			],
      			data:[],
      			page:1,
      			pageSize:10,
      			total:0,
      			nowTime:0,
      			tableLoading:false,
      			modalLoading:true,
                dateOptions: {
                    disabledDate (date) {
                        return date && date.valueOf() < Date.now() - 86400000;
                    }
                },
                vacationRules:{
                    deleUserId:[
                        {required: true, validator: validateDeleUserId, trigger: 'blur'}
                    ],
                    startTime: [
                        {required: true, validator: validateStartTime, trigger: 'change'},
                    ],
                    endTime: [
                        {required: true, validator: validateEndTime, trigger: 'change'},
                    ],
                    reason: [
                        {required: true, message: '请填写休假委托原因', trigger: 'blur'},
                    ]
                },
				peopleList:[],
				vacation: {
					id:0,
					userId:0,
					deleUserId:0,
					deleUserName:"",
					startTime:0,
					endTime:0,
					startDate:"",
					endDate:"",
					reason:"",
					isupdate: false
				},
				modal: false,
				userId:0,
				haveVacation:false
			}
		},
		mounted() {
			// this.userId = this.$store.state.user.id;
			this.getMyVacation(0);
		},
		methods:{
			getMyVacation(number){
				this.tableLoading = true;
				this.haveVacation = false;

		        if (number == 0) {
		          this.page = 1;
		        }

		        var pageModel = {};
		        pageModel.id = this.userId;
		        pageModel.page = this.page;
		        pageModel.pageSize = this.pageSize;

              	var that=this;
              	var url=this.CONFIG.url_know+'/getAllVacation';

              	ajax.post({
	              	url:url,
	              	that:that,
	              	data: pageModel,
	              	success:function(data){
	              		that.nowTime = Date.parse(new Date())/1000;
	              		data.vacationList.some(item=>{
	              			if(item.cancel === "0" && item.endTime > that.nowTime){
	              				that.haveVacation = true;
	              				return true;
	              			}
	              		});
	              		data.vacationList.forEach(item=>{
	                  		item.startDate = that.formatDate(item.startTime);
	                  		item.endDate = that.formatDate(item.endTime);
	              		});
	              		that.data = data.vacationList;
	              		that.total = data.total;
	              		that.tableLoading = false;
              		}
          		})
			},
			changePage(page) {
				this.page = page;
				this.getMyVacation(1);
			},
			changePageSize(pageSize) {
		        this.pageSize = pageSize;
		        this.getMyVacation(0);
		    },
			getPeople(data){
				console.log("getPeople---------->",data);
				this.vacation.deleUserId = data[0].id;
				this.vacation.deleUserName = data[0].user_name;
			},
			changeStartDate(date){
        		console.log("--------changeStartDate--------------",date);
        		if(date === undefined || date === null || date === ""){
        			this.vacation.startDate = "";
        			this.vacation.startTime = 0;
        		}else{
        			this.vacation.startDate = date;
        			var date = new Date(date);
        			this.vacation.startTime = (date.getTime() / 1000);
        			console.log("------------->",this.vacation.startTime);
        		}
			},
			changeEndDate(date){
        		console.log("--------changeEndDate--------------",date);
        		if(date === undefined || date === null || date === ""){
        			this.vacation.endDate = "";
        			this.vacation.endTime = 0;
        		}else{
        			this.vacation.endDate = date;
        			var date = new Date(date);
        			this.vacation.endTime = (date.getTime() / 1000);
        		}
			},
			addVacation(){
				console.log("-----haveVacation-------->",this.haveVacation);
				if(this.haveVacation){
					this.$Message.warning('已正在休假，不可重复休假!');
				}else{
					this.vacation = {
						id:0,
						userId:0,
						deleUserId:0,
						deleUserName:"",
						startTime:0,
						endTime:0,
						startDate:"",
						endDate:"",
						reason:"",
						isupdate:false
					};
					this.peopleList = [];
					this.modal = true;
				}
			},
			editVacation(row){
				this.peopleList = [];
                var j = {};
                j.id = row.deleUserId;
                j.user_name = row.deleUserName;
                this.peopleList.push(j);

				this.vacation = row;
				this.vacation.isupdate = true;
	            this.vacation.startDate = this.formatDate(row.startTime);
	            this.vacation.endDate = this.formatDate(row.endTime);
				this.modal = true;
				console.log("--------editVacation----------",this.vacation);
			},
			setVacation(){
				if (this.vacation.deleUserId === undefined || this.vacation.deleUserId === null || this.vacation.deleUserId < 1) {
	                this.messageWarningFn('被委托人不能为空!');
	                return
	            }else if(this.vacation.startTime === undefined || this.vacation.startTime === null || this.vacation.startTime < 1){
	                this.messageWarningFn('委托开始时间不能为空!');
	                return
	            }else if(this.vacation.endTime === undefined || this.vacation.endTime === null || this.vacation.endTime < 1){
	                this.messageWarningFn('委托结束时间不能为空!');
	                return
	            }else if(this.vacation.startTime >= this.vacation.endTime){
	                this.messageWarningFn('委托开始日期不能大于等于结束日期!');
	                return
	            }else if(this.vacation.reason === undefined || this.vacation.reason === null || this.vacation.reason === ""){
	                this.messageWarningFn('委托原因不能为空!');
	                return
	            }else if(this.vacation.deleUserId == this.$store.state.user.id){
	                this.messageWarningFn('不能委托给自己!');
	                return
	            }else{
	            	if(this.vacation.isupdate){
		              	var that=this;
		              	var url=this.CONFIG.url_know+'/updateVacation';

		              	ajax.post({
			              	url:url,
			              	that:that,
			              	data: this.vacation,
			              	success:function(data){
			                  	that.$Message.success('修改成功!');
			                  	that.modal = false;
			                  	that.getMyVacation(1);
		              		}
		          		})
	            	}else{
		              	var that=this;
		              	var url=this.CONFIG.url_know+'/addVacation';
		              	this.vacation.userId = this.userId;

		              	ajax.post({
			              	url:url,
			              	that:that,
			              	data: this.vacation,
			              	success:function(data){
			                  	if(data == 0){
			                  		that.$Message.error('提交失败!');
			                  	}else{
			                  		that.$Message.success('提交成功!');
			                  	}
			                  	that.modal = false;
			                  	that.getMyVacation(0);
		              		}
		          		})
	            	}
	            }

			},
			cancel(name){
				this.$refs[name].resetFields();
				this.getMyVacation(1)
			},
			cancelVacation(id){
				this.$Modal.confirm({
	                title:'确定取消休假？',
	                width:'360',
	                onOk:() => {
		              	var that=this;
		              	var url=this.CONFIG.url_know+'/cancelVacation/' + id;

		              	ajax.del({
			              	url:url,
			              	that:that,
			              	success:function(data){
			                  	that.$Message.success('已取消休假!');
			                  	that.$refs['vacationInfo'].resetFields();
			                  	that.getMyVacation(1);
		              		}
		          		})
	                }
              	});
			},
			messageWarningFn (text) {
				this.$Message.warning(text)
				setTimeout(() => {
				  this.modalLoading = false
				  this.$nextTick(() => {
				    this.modalLoading = true
				  });
				}, 0.1);
			},
			formatDate(date){
			  return this.utils.formatDate(new Date(date*1000), "yyyy-MM-dd hh:mm:ss")
			},
		}
	}
</script>